<template>
  <page-wrap :header-props="headerProps" :loading="loading">
    <template #extension>
      <div class="cm-order-header">
        <div class="cm-order-header-info">
          <div class="cm-order-header-left">
            <span class="cm-order-header__label">服务员：</span>
            <span class="cm-order-header__value cm-orange">{{
              cartStore.tableInfo.waiterUserName
            }}</span>
          </div>
          <div class="cm-order-header-right">
            <div class="cm-order-header__text">
              单号：{{ ls.get('PAY_TYPE') != 1 ? cartStore.orderBatchCode : ''}}
            </div>
          </div>
        </div>
        <div class="cm-order-header-panel">
          <div class="cm-order-header__remark">备注：{{ remarkMsg }}</div>
          <div class="cm-order-header__edit" @click="remarkShow = true"></div>
        </div>
      </div>
    </template>
    <div class="orderCashier-container">
      <div class="orderCashier-main">
        <div class="orderCashier-main-money">
          <div class="main-money-serve">
            <div class="serve-item" v-show="zkMoney.isSelected">
              折扣优惠:￥{{ formatDecimal(zkMoneyAmt) }}
            </div>
            <div class="serve-item" v-show="serveMoney.isSelected">
              服务费:￥{{ formatDecimal(serveMoneyAmt) }}
            </div>
            <div class="serve-item" v-show="giveChange.isSelected">
              抹零:￥{{ formatDecimal(giveChangeAmt) }}
            </div>
            <div class="serve-item" style="margin-right: 0" v-show="buMoney.isSelected">
              补低消:￥{{ formatDecimal(buMoneyAmt) }}
            </div>
          </div>
          <div class="orderCashier-main-money__label">待付金额</div>
          <div class="orderCashier-main-money__value">
            <div class="money__value-left">
              <span class="orderCashier-main-money__rmb">￥</span>
              <span class="orderCashier-main-money__price">{{
                formatDecimal(cartStore.unpaid)
              }}</span>
            </div>
            <div class="money__value-right" v-if="isShowMemberPrice">
              会员价：{{ formatDecimal(cartStore.vipOrderAmt) }}
            </div>
          </div>
          <div class="canusecoins">可用金币：￥{{ formatDecimal(cartStore.totalOrderAmt) }}</div>
          <div class="orderCashier-main-money__brother">
            <span class="span spe">预订押金：￥{{ toolBookAmt }}</span>
          </div>
          <div class="orderCashier-main-money__brother">
            <span class="span">总金额:￥{{ formatDecimal(cartStore.totalOrderAmt) }}</span>
            <span class="span">其它:￥{{ formatDecimal(totalSelectedMoney) }}</span>
            <span class="span spe">已付:￥{{ formatDecimal(cartStore.realPayAmt) }}</span>
          </div>
        </div>
        <div class="orderCashier-main-preferential" v-if="!isUpvip">
          <div class="preferential-title">其它项目</div>
          <div class="preferential-main" :class="{ disable: hasPay }">
            <div class="preferential-main-item spe"  v-if="ls.get('ORG_CODE') != '0024' && ls.get('ORG_CODE') != '0025'" @click="changeRadio" v-has-role="'waiter-checkout-rightsPrice'">
              <van-checkbox class="checkbox" v-model="memberPrice" label-disabled shape="round" checked-color="#17171a"
                icon-size="16px" disabled></van-checkbox>
              <!-- <van-radio v-model="memberPrice" ></van-radio> -->
              <div class="item-color-spe">权益价：￥{{ formatDecimal(cartStore.vipOrderAmt) }}</div>
            </div>
            <div class="preferential-main-item" :class="{ disable: !discountCon }">
              <van-checkbox class="checkbox" v-model="zkMoney.isSelected" label-disabled shape="square" :disabled="hasPay || !discountCon"
                checked-color="#17171a" icon-size="16px" @change="itemChange($event, 'discount')"></van-checkbox>
              <div class="item-color">折扣优惠</div>
              <div class="item-icon" v-if="isShowZkMoneyAmt"></div>
              <input class="dialog-cashpay-field__input" v-model="zkMoney.value" type="digit" autocomplete="off" :disabled="hasPay || !discountCon"
                @update:model-value="onCashChange($event, 'discount')" @blur="blurDis(zkMoney.value,'zkMoney')" oninput="value=value.replace(/[^0-9.]/g,'')"/>
              <van-dropdown-menu :overlay="false" class="select1">
                <van-dropdown-item v-model="serceSelected" :options="serceOptions" @change="discountChange" />
              </van-dropdown-menu>
            </div>
            <div class="preferential-main-item" :class="{ disable: !servicechargeCon }">
              <van-checkbox class="checkbox" v-model="serveMoney.isSelected" label-disabled shape="square" :disabled="hasPay || !servicechargeCon"
                checked-color="#17171a" icon-size="16px" @change="itemChange($event, 'tip')"></van-checkbox>
              <div class="item-color">服务费</div>
              <div class="item-icon" v-if="isShowServeMoneyAmt"></div>
              <input class="dialog-cashpay-field__input" v-model="serveMoney.value" type="digit" autocomplete="off" :disabled="hasPay || !servicechargeCon"
                @update:model-value="onCashChange($event, 'tip')" @blur="blurDis(serveMoney.value,'serveMoney')"  oninput="value=value.replace(/[^0-9.]/g,'')"/>
              <van-dropdown-menu :overlay="false" class="select2">
                <van-dropdown-item v-model="serveSelected" :options="serveOptions" @change="serveChange" />
              </van-dropdown-menu>
            </div>
            <div class="preferential-main-item" :class="{ disable: !supplyminconsumeCon }">
              <van-checkbox class="checkbox" v-model="buMoney.isSelected" label-disabled shape="square" :disabled="hasPay || !supplyminconsumeCon "
                checked-color="#17171a" icon-size="16px" @change="itemChange($event, 'minCount')"></van-checkbox>
              <div class="item-color">补低消</div>
              <div class="item-icon"></div>
              <input class="dialog-cashpay-field__input" v-model="buMoney.value" type="digit" autocomplete="off" :disabled="hasPay || !supplyminconsumeCon "
                @update:model-value="onCashChange($event, 'minCount')" @blur="blurDis(buMoney.value,'buMoney')" oninput="value=value.replace(/[^0-9.]/g,'')"/>
              <div class="item-color low">元</div>
              <div class="item-low">低消：{{ minConsume }}元</div>
            </div>
            <div class="preferential-main-item" :class="{ disable: !rounddownCon }">
              <van-checkbox class="checkbox" v-model="giveChange.isSelected" label-disabled shape="square" :disabled="hasPay || !rounddownCon"
                checked-color="#17171a" icon-size="16px"  @change="itemChange($event, 'smallChange')"></van-checkbox>
              <div class="item-color">抹零</div>
              <div class="item-icon"></div>
              <input class="dialog-cashpay-field__input" v-model="giveChange.value" type="digit" autocomplete="off" :disabled="hasPay || !rounddownCon"
                @update:model-value="onCashChange($event, 'smallChange')" @blur="blurDis(giveChange.value,'giveChange')" oninput="value=value.replace(/[^0-9.]/g,'')"/>
              <div class="item-color">元</div>
            </div>
          </div>
        </div>
        <div class="orderCashier-main-pay">
          <div class="orderCashier-main-section-title">收款方式选择</div>
          <ul class="orderCashier-main-pay-list">
            <li class="orderCashier-main-pay-item" v-for="(v, k) in payList" :key="k" @click="onPayWay(v.name)" v-has-role="v.role">
              <img class="orderCashier-main-pay__cover"  :src="v.icon" alt="SVG Icon" />
              <div class="orderCashier-main-pay__way" >{{ v.value }}</div>
            </li>
          </ul>
        </div>
        <div class="orderCashier-main-record">
          <div class="orderCashier-main-section-title">收款记录</div>
          <ul class="orderCashier-main-record-list">
            <li class="orderCashier-main-record-item" v-for="(v, k) in recordList" :key="k">
              <div class="orderCashier-main-record__info">
                <div class="orderCashier-main-record__way">
                  {{ v.payTypeName }}支付
                </div>
                <div class="orderCashier-main-record__time">
                  {{ dayjs(v.crDate).format('YYYY-MM-DD HH:mm:ss') }}
                </div>
              </div>
              <!-- <div :class="{'orderCashier-main-record__money':true,'red':v.type==1,'green':v.type==2}">￥{{v.totalAmt}}</div> -->
              <div :class="{ 'orderCashier-main-record__money': true, red: true }">
                <div class="record-value" :class="{ red: v.state == 4 }">
                  <span v-if="v.state == 4">-</span><span v-if="v.state == 2">+</span>￥{{
                    formatDecimal(v.realAmt)
                  }}
                </div>
                <div class="record-back" v-if="v.state == 2" @click="payBack(v)">
                  退款
                </div>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="orderCashier-footer">
        <div class="orderCashier-footer-button" v-has-role="'waiter-checkout-cancel'"  @click="cancelOrderShow = true">
          取消支付
        </div>
        <div class="orderCashier-footer-button spe" v-has-role="'waiter-checkout'" @click="onCheckout">
          结账
        </div>
      </div>
    </template>
  </page-wrap>

  <!-- 会员弹窗 -->
  <z-popup v-model:show="memberShow">
    <div class="popup-pay-member">
      <div class="popup-pay-form">
        <div class="popup-pay-form-item">
          <input  v-model="cartStore.account" class="popup-pay-form__input" placeholder="请输入会员卡号/手机号" />
          <img class="popup-pay-form__icon" :src="i_cashier_scan" @click="qrScannerShow = true" />
        </div>
        <div class="popup-pay-form-control">
          <z-button @click="onMember">验证会员卡</z-button>
        </div>
      </div>
    </div>
  </z-popup>
  <!-- 验证会员能否使用会员价弹窗 -->
  <z-popup v-model:show="memberPriceShow">
    <div class="popup-pay-member">
      <div class="popup-pay-form">
        <div class="popup-pay-form-item">
          <input  v-model="cartStore.account" class="popup-pay-form__input" placeholder="请输入会员卡号/手机号" />
          <img class="popup-pay-form__icon" :src="i_cashier_scan" @click="qrScannerShow = true" />
        </div>
        <div class="popup-pay-form-control">
          <z-button @click="onMemberPrice">验证会员卡</z-button>
        </div>
      </div>
    </div>
  </z-popup>
  <!-- 开通会员弹窗 -->
  <z-dialog v-model:show="openMemberShow" content="是否前往开通会员？" @confirm="onOpenMember"></z-dialog>

  <!-- 收款二维码弹窗 -->
  <z-popup v-model:show="qrcodeShow" closeable :close-on-click-overlay="false" :before-close="onCloseQRCode"
    @closed="onClosedQRCode" :title="cartStore.tableInfo.roomName">
    <div class="popup-collect">
      <div class="popup-collect-title">
        {{ formatDecimal(cartStore.unpaid) }}<span class="unit">元</span>
      </div>
      <div class="popup-collect-subtitle">{{ cartStore.payInfo.payType }}</div>
      <div class="popup-collect-cover" ref="myCanvas">
        <!-- <div class="popup-collect-overlay" :style="{ width: `${myCanvasWidth}px`, height: `${myCanvasWidth}px` }" v-if="cartStore.expire">收款码已失效<br>请点击下方刷新按钮</div> -->
        <div class="popup-collect-overlay" v-if="cartStore.expire">
          收款码已失效<br />请点击下方刷新按钮
        </div>
        <img class="popup-collect-baseUrl" :src="cartStore.payInfo.qrCode" />
        <!-- <div class="popup-collect-code" :style="{ width: `${myCanvasWidth}px`, height: `${myCanvasWidth}px` }">
                    <vue-qrcode :value="cartStore.payInfo.qrCode" :options="{ width:myCanvasWidth }"></vue-qrcode>
                </div> -->
      </div>
      <div class="popup-collect-panel">
        <div class="popup-collect-countdown" v-if="cartStore.expire">
          {{ cartStore.countValue }}
        </div>
        <div class="popup-collect-countdown" v-else>
          收款码<span class="highlight">{{ cartStore.countValue }}</span>秒后失效
        </div>
        <div :class="{
          'popup-collect-refresh': true,
          disabled: !cartStore.expire
        }" @click="onRefreshQRCode">
          刷新
        </div>
      </div>
    </div>
  </z-popup>

  <!-- 关闭收款的二次确认 -->
  <z-dialog v-model:show="cancelPayShow" content="关闭后客户无法继续支付，是否确认关闭？" @confirm="onCancelPay"></z-dialog>

  <!-- 扫描二维码弹窗 -->
  <QRScanner v-model:show="qrScannerShow" @success="onScanSuccess"></QRScanner>

  <!-- 修改备注 -->
  <z-dialog v-model:show="remarkShow" title="修改备注" style="width: 300px" @confirm="onConfirmRemark">
    <div class="popup-remark">
      <van-field v-model="remarkEditMsg" rows="2" type="textarea" placeholder="请输入备注" />
    </div>
  </z-dialog>

  <!-- 现金支付弹窗 -->
  <z-dialog v-model:show="cashPayShow" title="现金支付" style="width: 460px" @confirm="onPay('001')" @opened="onOpenedCashPay">
    <div class="dialog-cashpay">
      <div class="dialog-cashpay-title">
        未付金额<span style="color: #ffaa00">{{
          formatDecimal(cartStore.unpaid)
        }}</span>元
      </div>
      <!-- <div class="dialog-cashpay-field">
                <div class="dialog-cashpay-field__label">抹零</div>
                <div class="dialog-cashpay-field__group">
                    <van-field class="dialog-cashpay-field__input" v-model="payListForm.smallChange" type="digit" placeholder="请输入抹零金额"  autocomplete="off" @update:model-value="onCashChange($event, 'smallChange')" />
                    <div class="dialog-cashpay-field__right">元</div>
                </div>
            </div> -->
      <!-- <div class="dialog-cashpay-title">待付<span class="highlight">{{formatDecimal(unpaid)}}</span>元</div> -->
      <div class="dialog-cashpay-field">
        <!-- <div class="dialog-cashpay-field__label">现金</div> -->
        <div class="dialog-cashpay-field__group">
          <van-field class="dialog-cashpay-field__input" v-model="payListForm.payAmt" type="number"
            placeholder="请输入收取现金金额" autocomplete="off" @update:model-value="onCashChange($event, 'payAmt')" />
          <div class="dialog-cashpay-field__right">元</div>
        </div>
      </div>
      <!-- <div class="dialog-cashpay-title">应找零<span class="highlight">{{formatDecimal(payListForm.giveChange)}}</span>元</div> -->
      <div class="dialog-cashpay-title spe">
        找零金额：<span class="highlight">{{
          formatDecimal(payListForm.giveChange)
        }}</span>元
      </div>
      <div class="dialog-cashpay-give">
        <!-- <van-checkbox class="checkbox" v-model="notGive.isSelected" label-disabled checked-color="#17171a"
          icon-size="16px" @change="itemChange($event, 'discount')"></van-checkbox> -->
        <div class="give-title">不设找赎</div>
        <van-field class="dialog-cashpay-field__input" v-model="payListForm.notGiveChange" type="number"
          placeholder="请输入收取现金金额" autocomplete="off" @update:model-value="onCashChange($event, 'giveChange')" />
      </div>
    </div>
  </z-dialog>

  <!-- 取消订单确认弹窗 -->
  <z-dialog v-model:show="cancelOrderShow" content="是否确认取消支付？" @confirm="onCancelOrder"></z-dialog>

  <!-- 微信支付宝确认提示弹窗 -->
  <z-dialog v-model:show="onlineWxPay" content="客户支付成功后会自动关闭页面，在此之前不要关闭页面！！！" @confirm="confirmOnlineWxPay"></z-dialog>
  <z-dialog v-model:show="onlineAliPay" content="客户支付成功后会自动关闭页面，在此之前不要关闭页面！！！" @confirm="confirmOnlineAliPay"></z-dialog>


</template>
<script setup>
import dayjs from 'dayjs'
import useCartStore from '@/store/cart'
import useAppStore from '@/store/app'
import Api from '@/api'
import { showToast } from 'vant'
import _ from 'lodash'
import ls from '@/lib/ls'
import QRCode from 'qrcode'
import VueQrcode from '@chenfengyuan/vue-qrcode'
import { formatNumber, formatDecimal,calculateOrderQty } from '@/lib/util.js'

import i_pay_member from '@/assets/images/open/i_pay_member.png'
import i_pay_alipay from '@/assets/images/open/i_pay_alipay.png'
import i_pay_wechat from '@/assets/images/open/i_pay_wechat.png'
import i_pay_qrcode from '@/assets/images/open/i_pay_qrcode.png'
import i_pay_cash from '@/assets/images/open/i_pay_cash.png'
import i_pay_pos from '@/assets/images/open/i_pay_pos.png'
import i_pay_sign from '@/assets/images/open/i_pay_sign.png'
import i_cashier_scan from '@/assets/images/open/i_cashier_scan.png'
import { watch } from 'vue'
import { nextTick } from 'vue'

const router = useRouter()
const route = useRoute()
const cartStore = useCartStore()
const appStore = useAppStore()
const memberShow = ref(false)
const memberPriceShow = ref(false)
const qrcodeShow = ref(false)
const cancelPayShow = ref(false)
const qrScannerShow = ref(false)
const remarkShow = ref(false)
const remarkMsg = ref(cartStore.tableInfo.consumeRemark)
const remarkEditMsg = ref('')
const cashPayShow = ref(false)
const openMemberShow = ref(false)
const loading = ref(false)
const cancelOrderShow = ref(false)
const polling = ref(undefined)
const isInit = ref(false)

const onlineWxPay = ref(false)
const onlineAliPay = ref(false)


const isShowMemberPrice = ref(true) // 是否显示会员价
const minConsume = ref('') // 房台低消
if(ls.get('TABLE_INFO')){
  console.log(ls.get('TABLE_INFO'));
  
  minConsume.value = ls.get('TABLE_INFO').consumeMinConsume
}

console.log(minConsume.value);

watch(cartStore.wsPayState,(newValue,oldValue)=>{
  if(cartStore.wsPayState.consumeCode == ls.get('TABLE_INFO').consumeCode){
    alert('PC端在操作当前房台支付状态')
    router.replace({
      path: '/open',
    })
  }
  
})

const payList = [
  {
    name: 'member',
    icon: i_pay_member,
    value: '会员卡',
    role:'waiter-checkout-membercard'
  },
  {
    name: 'cash',
    icon: i_pay_cash,
    value: '现金',
    role:'waiter-checkout-cash'
    
  },
  {
    name: 'wechat',
    icon: i_pay_wechat,
    value: '微信',
    role:'waiter-checkout-weChat'
  },
  {
    name: 'alipay',
    icon: i_pay_alipay,
    value: '支付宝',
    role:'waiter-checkout-alipay'
  }
  // {
  //     name: 'qrcode',
  //     icon: i_pay_qrcode,
  //     value: '扫码收款'
  // },
  // {
  //     name: 'pos',
  //     icon: i_pay_pos,
  //     value: 'POS支付'
  // }
]

const recordList = ref([])

// 头部props
const headerProps = computed(() => {
  const r = {
    backFn: () => {
      cancelOrderShow.value = true
      // if (cartStore.orderBatchCode != '') {
      //   router.push({
      //     path: '/open'
      //   })
      //   cartStore.ClearState()
      //   ls.remove('PAY_BATCH_CODE')
      //   ls.remove('TABLE_INFO')
      //   ls.remove('MEMBER_CARD_NUMBER')
      //   ls.remove('PAY_INFO')
      //   // unref(polling).stop()
      //   // onCancelQRCode()
      // } else {
      //   router.back()
      // }
    }
  }
  return r
})

// --------------------------------------------------------------- 优惠项目 ---------------------------------------------------
// 会员价选择
const memberPrice = ref(false)
const changeRadio = (e) => {
  if(hasPay.value){
    showToast('已有支付记录，无法使用权益')
    return
  }
  console.log(memberPrice.value);
  if (!memberPrice.value) {
    memberPriceShow.value = true
  } else {
    cartStore.vipDiscount = 0
    memberPrice.value = false
  }
}

// 复选框
const itemChange = (e, name) => {
  console.log(e, name)
  switch (name) {
    case 'smallChange':
      giveChange.value.isSelected = e
      console.log(giveChange.value.isSelected)
      break
    case 'discount':
      zkMoney.value.isSelected = e
      break
    case 'tip':
      serveMoney.value.isSelected = e
      break
    case 'minCount':
      buMoney.value.isSelected = e
      if(Number(minConsume.value) > (Number(cartStore.totalOrderAmt) + Number(payed.value))){
        buMoney.value.value = formatDecimal(minConsume.value-cartStore.totalOrderAmt-payed.value)
        buMoneyAmt.value = formatDecimal(minConsume.value-cartStore.totalOrderAmt-payed.value)
      }
      break
  }
  cartStore.discountAmt = totalSelectedMoney // 给优惠赋值
}
const giveChangeAmt = ref(0) // 抹零金额(头部显示)
const giveChange = ref({
  // 抹零
  isSelected: false,
  value: 0
})
const notGive = ref({
  // 不找赎
  isSelected: false,
  value: 0
})
const isShowZkMoneyAmt = ref(true)
const zkMoneyAmt = ref(0) // 折扣金额（头部显示）
const zkMoney = ref({
  // 折扣金额
  isSelected: false,
  value: 0
})
const isShowServeMoneyAmt = ref(true)
const serveMoneyAmt = ref(0) // 服务费金额（头部显示）
const serveMoney = ref({
  // 服务费
  isSelected: false,
  value: 0
})
const buMoneyAmt = ref(0) // 补低消费金额（头部显示）
const buMoney = ref({
  // 补低消费
  isSelected: false,
  value: 0
})
const serceSelected = ref(0) // 折扣优惠
const serveSelected = ref(0) // 服务费
const serceOptions = [
  { text: '按优惠金额（元）', value: 0 },
  { text: '按折扣优惠（折）', value: 1 },
  { text: '按付款金额（元）', value: 2 }
]
// 折扣优惠单位调整
const discountChange = e => {
  console.log(e)
  zkMoney.value.value = 0
  zkMoneyAmt.value = 0
  if (e == 1) {
    isShowZkMoneyAmt.value = false
  } else {
    isShowZkMoneyAmt.value = true
  }
}
// 服务费单位调整
const serveChange = e => {
  serveMoney.value.value = 0
  serveMoneyAmt.value = 0
}
const serveOptions = [
  { text: '元', value: 0 },
  { text: '%', value: 1 }
]
// 优惠总金额
const totalSelectedMoney = computed(() => {
  let sum = 0
  if (giveChange.value.isSelected) {
    sum += Number(giveChangeAmt.value)
  }
  if (zkMoney.value.isSelected) {
    sum += Number(zkMoneyAmt.value)
  }
  if (serveMoney.value.isSelected) {
    sum -= Number(serveMoneyAmt.value)
  }
  if (buMoney.value.isSelected) {
    sum -= Number(buMoneyAmt.value)
  }
  return sum
})
watch(totalSelectedMoney, (newVal, oldVal) => {
    console.log(newVal);
    
    if(newVal >= cartStore.totalOrderAmt){
        alert('优惠金额不能超过订单总金额')
        giveChange.value.value = 0
        zkMoney.value.value = 0   
        serveMoney.value.value = 0  
        buMoney.value.value = 0
        giveChangeAmt.value = 0
        zkMoneyAmt.value = 0
        serveMoneyAmt.value = 0
        buMoneyAmt.value = 0
    }
});

const postForm = reactive({
  // 消费单号
  consumeCode: '',
  // 房台编码
  roomCode: '',
  // 付款人(代付)，（服务员）
  payUser: '',
  // 批次号(首次买单为空,后续再买单将首次的批次号传入)
  payBatchCode: '',
  // 收银员 - 传空
  cashUser: '',
  // 付款商品列表(使用点单的itemCode)
  detailList: '',
  // 商品单号
  tradeNo: '',
  // detailList: cartStore.goodsOrderStr,
  // 点单商品金额
  orderAmt: '',
  // 实际收款金额
  realPayAmt: '',
  // 支付方式(001现金 002微信 003支付宝 004会员卡 005消费卷 006银联 007其他 008挂账 009聚合支付 010团购券 011赠送 012会员优惠券)
  payType: '',
  /*
   * 支付列表(手机端只有一条,电脑端可能有多条)
   * @totalAmt 本条的付款金额
   * @payAmt 客人付款金额(现金可能大于点单金额,需要有找零和抹零,其他方式totalAmt == payAmt)
   * @giveChange 找零金额
   * @smallChange 抹零金额
   * @memberCode 会员编码(会员付款) - 传空
   * @memberName 会员姓名 - 传空
   * @memberMobile 电话 - 传空
   * @memberOpenId openid - 传空
   * @payType 支付方式(001 现金002微信003支付宝004会员卡005消费卷)
   */
  payList: [],
  /*
   *"code": "买单批次号",
   *"type": "抹零/服务费/折扣优惠/补低消",
   *"subType": "子类型",
   *"amt": "服务费类型"
   */
  serviceAmt: [] // 优惠项目
})
const toolZLAmt = ref(0)
// 支付列表(手机端只有一条,电脑端可能有多条)
const payListForm = reactive({
  // 本条的付款金额
  totalAmt: '',
  // 客人付款金额（现金可能大于点单金额,需要有找零和抹零,其他方式totalAmt == payAmt）
  payAmt: '',
  // 找零金额
  giveChange: '',
  // 抹零金额
  smallChange: '',
  // 会员编码（会员付款）
  memberCode: '',
  // 会员姓名
  memberName: '',
  // 电话
  memberMobile: '',
  // openid
  memberOpenId: '',
  // 支付方式（001现金 002微信 003支付宝 004会员卡 005消费卷）
  payType: '',
  // 找赎金额(现金支付需要传)
  notGiveChange: '',
  // 挂账人名称(挂账支付需要传)
  mountUser: '',
  // 挂账人手机号(挂账支付需要传
  mountMobile: '',
  // 挂账人性别(字典数据编号011)(挂账支付需要传)
  mountSex: '',
  // 担保人编号,服务员数据(挂账支付需要传)
  suretyUser: '',
  // 赠送人服务员数据(赠送支付需要传)
  giftUser: '',
  // 赠送备注(赠送支付需要传)
  giftRemark: ''
})
const serviceAmtForm = ref({
  code: '',
  type: '',
  subType: '',
  amt: '',
  toolAmt: ''
})
// 现金表单变化的联动
const initCashForm = ref(false)
const unpaid = ref('')
const blurDis = (val,type)=>{
  const regex = /^\d+(\.\d+)?$/;
  if (!regex.test(val)) {
      val = ''; // 清空输入框，或者进行其他处理
  }
  switch (type) {
    case 'giveChange':
      
      break;
  
    case 'discount':
      
      break;
    case 'serveMoney':
      
      break;
    case 'buMoney':
      
      break;
  }
  return
  if(serceSelected.value == 1){
      if ( val < 0.1) {
        zkMoney.value.value = 0.1
        zkMoneyAmt.value = formatDecimal(cartStore.totalOrderAmt - cartStore.totalOrderAmt * (0.1 * 0.1))
      }
  }

}
const onCashChange = (val, type) => {
  console.log(val);
  const regex = /^\d+(\.\d+)?$/;
  if (!val) {
    val = 0
  }
  if (!regex.test(val)) {
      val = 0 
  }
  // if (!unref(initCashForm)) return
  // switch(type) {
  //     case 'payAmt':
  //         if (payListForm.payAmt > unref(unpaid)) {
  //             payListForm.giveChange = formatDecimal(Number(val) - Number(unref(unpaid)))
  //         } else {
  //             payListForm.giveChange = 0
  //         }
  //         break;
  //     case 'giveChange':

  //         break;
  //     case 'smallChange':
  //             if (Number(val) > cartStore.unpaid) {
  //                 payListForm.smallChange = cartStore.unpaid
  //             }
  //             unpaid.value = cartStore.totalOrderAmt - cartStore.payAmt - cartStore.smallChange - Number(val)
  //             if (payListForm.payAmt > unref(unpaid)) {
  //                 payListForm.giveChange = formatDecimal(Number(payListForm.payAmt) - Number(unref(unpaid)))
  //             } else {
  //                 payListForm.giveChange = 0
  //             }
  //         break;
  // }
  switch (type) {
    case 'smallChange': // 抹零
      if (val > 10) {
        showToast('抹零金额不能大于10')
        giveChange.value.value = 10
        giveChangeAmt.value = 10
      } else {
        giveChangeAmt.value = val
      }
      if (val < 0) {
        giveChange.value.value = 0
        giveChangeAmt.value = 0
        showToast('金额不能为负数')
      }
      break

    case 'discount': // 折扣优惠
      if (val < 0) {
        zkMoney.value.value = 0
        zkMoneyAmt.value = 0
        showToast('金额不能为负数')
        return
      }
      if (serceSelected.value == 0) {
        // 优惠金额（元）
        zkMoneyAmt.value = formatDecimal(val)
      } else if (serceSelected.value == 1) {
        console.log(val);
        if(val == 0){
          zkMoneyAmt.value = 0
          return
        }
        zkMoneyAmt.value = formatDecimal(
          cartStore.totalOrderAmt - cartStore.totalOrderAmt * (val * 0.1)
        )
        console.log(val);
        
        // 折扣优惠（%）
        if ( val > 9.9) {
          val = 0
          zkMoney.value.value = 0
          zkMoneyAmt.value = 0
        }
      } else {
        // 付款金额（元）
        zkMoneyAmt.value = formatDecimal(cartStore.totalOrderAmt - val)
      }
      break

    case 'tip': // 服务费
      if (val < 0) {
        serveMoney.value.value = 0
        serveMoneyAmt.value = 0
        showToast('金额不能为负数')
        return
      }
      console.log(serveSelected.value)
      if (serveSelected.value == 0) {
        // 固定金额
        serveMoneyAmt.value = formatDecimal(val)
      } else {
        // 百分比
        serveMoneyAmt.value = cartStore.totalOrderAmt * (val * 0.01)
         // 折扣优惠（%）
        //  if ( val > 9.99) {
        //   val = 0
        //   serveMoney.value.value = 0
        //   serveMoneyAmt.value = 0
        // }
      }
      break

    case 'minCount': // 补低消
      if (val < 0) {
        buMoney.value.value = 0
        buMoneyAmt.value = 0
        showToast('金额不能为负数')
        return
      }
      if(val == 0){
          buMoneyAmt.value = 0
          return
      }
      if(Number(val) + cartStore.totalOrderAmt > minConsume.value){
        buMoney.value.value = 0
        buMoneyAmt.value = 0
        showToast('补低消金额不能超过'+ formatDecimal(minConsume.value-cartStore.totalOrderAmt)+'元')
        return
      }
      buMoneyAmt.value = Number(val)
      break

    case 'payAmt': // 现金支付
      if (val < 0) {
        val = 0
        showToast('金额不能为负数')
        return
      }
      if (payListForm.payAmt > unref(unpaid)) {
        payListForm.giveChange = formatDecimal(
          Number(val) - Number(unref(unpaid))
        )
      } else {
        payListForm.giveChange = 0
        payListForm.notGiveChange = 0
      }
      toolZLAmt.value = payListForm.giveChange
      break

    case 'giveChange': // 不找赎
      if (val < 0) {
        val = 0
        showToast('金额不能为负数')
        return
      }
      if(payListForm.notGiveChange >= 0){
        payListForm.giveChange = Number(toolZLAmt.value) - Number(payListForm.notGiveChange)
      }
      if (Number(payListForm.notGiveChange) >= Number(toolZLAmt.value)) {
        payListForm.notGiveChange = toolZLAmt.value
        payListForm.giveChange = 0
      }
      if(payListForm.notGiveChange >0){
        notGive.value.isSelected = true
      }else{
        notGive.value.isSelected = false
      }
      break
  }

}

// 打开弹窗后执行
const onOpenedCashPay = () => {
  initCashForm.value = true
}

// orderPay接口报错的兼容
const timeoutId = ref(null)
const retryCount = ref(0)
const executeFunction = () => {
  timeoutId.value = setTimeout(() => {
    cartStore.payInfo = ls.get('PAY_INFO')
    if (unref(retryCount) >= 2) {
      clearTimeout(unref(timeoutId))
      showToast('系统出错，请联系管理员')
      loading.value = false
      ls.remove('PAY_INFO')
      cartStore.ClearPayInfo()
      router.replace('/open')
      return
    } else {
      retryCount.value++
      if (retryCount.value >= 2) {
        clearTimeout(unref(timeoutId))
        return
      }
      getPayState(cartStore.payInfo.tradeNo, cartStore.payInfo.payWay)
    }
  }, 5e3)
}
let flag = ref(false)
const bookAmtTool = ref({})
// 支付
const onPay = async(way) => {
  if(payListForm.payAmt < 0){
      showToast('支付金额不能为负数')
      return
  }
  loading.value = true
  postForm.payList = []

  // 支付方式
  payListForm.payType = way
  postForm.payType = way
  memberUpPayList.value.payType = way
  if (way == '001') {
    // 本条的付款金额
    payListForm.totalAmt = formatDecimal(
      Number(payListForm.payAmt) - Number(payListForm.giveChange) - Number(payListForm.notGiveChange)
    )
    // 客人付款金额
    payListForm.payAmt = formatDecimal(Number(payListForm.payAmt))
    // 找零金额
    payListForm.giveChange = formatDecimal(Number(payListForm.giveChange))
    // 找赎金额
    // payListForm.notGiveChange
    // 抹零金额
    // payListForm.smallChange = formatDecimal(Number(payListForm.smallChange))
    // 实际收款金额
    postForm.realPayAmt = formatDecimal(
      Number(payListForm.payAmt) -
      Number(payListForm.giveChange) +
      Number(payListForm.smallChange)
    )
    if (!notGive.value.isSelected) {
      payListForm.notGiveChange = 0
    }
  }
  if (way == '002' || way == '003') {
    // 成功后的买单表单赋值
    payListForm.totalAmt = formatDecimal(Number(cartStore.unpaid))
    payListForm.payAmt = formatDecimal(Number(cartStore.unpaid))
    postForm.realPayAmt = formatDecimal(Number(payListForm.totalAmt))
    payListForm.tradeNo = cartStore.payInfo.tradeNo
    postForm.tradeNo = cartStore.payInfo.tradeNo
    memberUpPayList.value.tradeNo = cartStore.payInfo.tradeNo
  }
  // 赋值消费批次号
  postForm.payBatchCode = cartStore.payBatchCode
  // 点单商品金额
  postForm.orderAmt = cartStore.totalOrderAmt
  // 支付列表
  postForm.payList.push(payListForm)
  console.log(payListForm);
  
  
  
  otherPay() // 其它项目添加
  // console.log('---------')
  // console.log(postForm)
  // 会员卡升级支付
  if (route.query.type == 'levelUp') {
    memberUpPay() // 会员升级支付
    return
  }
  let orderInfo = ls.get('ORDER_INFO')
      // cartStore.orderBatchCode = res.orderBatchCode
      // ls.set('ORDER_BATCH_CODE', res.orderBatchCode)
      // cartStore.goodsOrderStr = res.dataList.map(obj => obj.itemCode).join(',')
      // postForm.detailList = cartStore.goodsOrderStr
      // onCancelOrderForm.value.itemCodeList = cartStore.goodsOrderStr // 取消订单接口参数
  if (orderInfo && orderInfo.dataList) {
    postForm.detailList = orderInfo.dataList.map(obj => obj.itemCode).join(',')
  }
  if (way == '002' || way == '003') { // 微信支付宝临时买单
    await lsPayOrder(postForm) // 支付
  }else{ // 其它支付正常买单
    await payOrder(postForm) // 支付
  }

  // 买单
  // if (ls.get('PAY_TYPE') == 1) {
    
  //     console.log(res)
  //     cartStore.orderBatchCode = res.orderBatchCode
  //     ls.set('ORDER_BATCH_CODE', res.orderBatchCode)
  //     cartStore.goodsOrderStr = res.dataList.map(obj => obj.itemCode).join(',')
  //     postForm.detailList = cartStore.goodsOrderStr
  //     onCancelOrderForm.value.itemCodeList = cartStore.goodsOrderStr
  //     console.log(cartStore.orderBatchCode)
  //     console.log(cartStore.goodsOrderStr)
  //     // serviceAmtForm.code =
  //      payOrder(postForm) // 支付
  // } else {
  //   await payOrder(postForm) // 支付
  // }
  if(bookAmt.value > 0){
    let obj = {
      cardNo : bookCardNo.value,
      tradeNo : bookTradeNo.value,
      payType : bookPayType.value,
      payAmt : bookAmt.value,
      totalAmt : bookAmt.value,
      isReservePay:'1'
    }
    postForm.payList = [obj]
    postForm.payType = bookPayType.value
    postForm.realPayAmt = bookAmt.value
    postForm.tradeNo = bookTradeNo.value
    bookAmtTool.value = postForm
  }
}
// 退款
const payBackForm = ref({
  payType: '', // payType:方式编号 支付方式(001现金 002微信 003支付宝 004会员卡 005消费卷 006银联 007其他 008挂账 009聚合支付 010团购券 011赠送 012 会员优惠券撤销)
  itemCode: '', // 支付交易流水号
  amt: '', // 支付金额
  payBatchCode: '', // 买单批次号
  consumeCode: '', // 台单号
  cardNo: '', // 会员卡号
  tradeNo: '' // 微信和支付宝支付返回的tradeNo
})
const payBack = d => {
  console.log(d)
  if (route.query.type == 'levelUp') {
    Api.Common.AppObjProcess.Do({
      functionName: 'MemberUpPayRet',
      contentData: { itemCodes: d.itemCode }
    })
      .then(res => {
        showToast(res.result)
        memberUpPayRecord()
      })
    return
  }
  payBackForm.value.payType = d.payTypeCode
  payBackForm.value.itemCode = d.itemCode
  payBackForm.value.amt = d.realAmt
  payBackForm.value.payBatchCode = d.payBatchCode
  payBackForm.value.consumeCode = ls.get('TABLE_INFO').consumeCode
  payBackForm.value.cardNo = d.carNo
  payBackForm.value.tradeNo = d.tradeNo
  console.log(payBackForm.value)
  // return
  Api.Common.AppObjProcess.Do({
    functionName: 'OrderPayRet',
    contentData: payBackForm.value
  }).then(res => {
    showToast(res.result)
    getBuyRecord()
  })
}
// ------------------------------------------------------------------ 其它项目 ---------------------------------------------------------
const otherPay = () => {
  serviceAmtForm.value.code = ls.get('PAY_BATCH_CODE')
  giveChangePay() // 抹零
  zkMoneyPay() // 折扣优惠
  serveMoneyPay() // 服务费
  buMoneyPay() // 补低消
  useMemberPrice() // 会员价
  ls.set('SERVICE_AMT', postForm.serviceAmt)
}

const giveChangePay = () => {
  let obj = {}
  console.log(giveChange.value.isSelected)
  if (giveChange.value.isSelected == true) {
    serviceAmtForm.value.type = '抹零'
    serviceAmtForm.value.subType = '正向抹零'
    serviceAmtForm.value.amt = giveChangeAmt.value
    serviceAmtForm.value.toolAmt = giveChange.value.value
    obj = { ...serviceAmtForm.value }
    postForm.serviceAmt.push(obj)
    console.log(postForm.serviceAmt)
    console.log(obj)
  }
}
const zkMoneyPay = () => {
  let obj = {}
  console.log(zkMoney.value.isSelected == true)
  if (zkMoney.value.isSelected == true) {
    serviceAmtForm.value.type = '折扣优惠'
    if (serceSelected.value == 0) {
      serviceAmtForm.value.subType = '按金额优惠'
    } else if (serceSelected.value == 1) {
      serviceAmtForm.value.subType = '按折扣优惠'
    } else {
      serviceAmtForm.value.subType = '输入付款金额'
    }
    serviceAmtForm.value.toolAmt = zkMoney.value.value
    serviceAmtForm.value.amt = zkMoneyAmt.value
    obj = { ...serviceAmtForm.value }
    postForm.serviceAmt.push(obj)
    console.log(postForm.serviceAmt)
    console.log(obj)
  }
}
const serveMoneyPay = () => {
  let obj = {}
  console.log(serveMoney.value.isSelected == true)
  if (serveMoney.value.isSelected == true) {
    serviceAmtForm.value.type = '服务费'
    if (serveSelected.value == 0) {
      serviceAmtForm.value.subType = '按固定金额'
    } else {
      serviceAmtForm.value.subType = '按百分比'
    }
    serviceAmtForm.value.toolAmt = serveMoney.value.value
    serviceAmtForm.value.amt = serveMoneyAmt.value
    obj = { ...serviceAmtForm.value }
    postForm.serviceAmt.push(obj)
    console.log(postForm.serviceAmt)
    console.log(obj)
  }
}
const buMoneyPay = () => {
  let obj = {}
  console.log(buMoney.value.isSelected == true)
  if (buMoney.value.isSelected == true) {
    serviceAmtForm.value.type = '补低消'
    serviceAmtForm.value.subType = ''
    serviceAmtForm.value.toolAmt = buMoney.value.value
    serviceAmtForm.value.amt = buMoneyAmt.value
    obj = { ...serviceAmtForm.value }
    postForm.serviceAmt.push(obj)
    console.log(postForm.serviceAmt)
    console.log(obj)
  }
}
// 会员价
const useMemberPrice = () => {
  let obj = {}
  if (memberPrice.value) {
    serviceAmtForm.value.type = '会员折扣优惠'
    serviceAmtForm.value.subType = ''
    serviceAmtForm.value.toolAmt = cartStore.vipDiscount
    serviceAmtForm.value.amt = cartStore.vipDiscount
    obj = { ...serviceAmtForm.value }
    postForm.serviceAmt.push(obj)
    console.log(postForm.serviceAmt)
    console.log(obj)
  }
}
// ------------------------------------------------------------------- 调用支付接口 ---------------------------------------------------------------
const payOrder = async(form) => {
  Api.Common.AppObjProcess.Do({
    functionName: 'orderPay',
    contentData: form
  })
    .then(async res => {
      // 成功
      console.log(res)
      // console.log(res)
      // console.log(res)
      // 关闭支付弹窗
      cashPayShow.value = false
      setTimeout(() => {
        loading.value = false
        flag.value = false
      }, 1000)

      // 存 - 消费批次号
      cartStore.payBatchCode = res.payBatchCode
      ls.set('PAY_BATCH_CODE', res.payBatchCode)
      
      // 存 - 已付金额
      // cartStore.payAmt = res.payAmt
      // cartStore.giveChange = res.giveChange
      // cartStore.smallChange = res.smallChange
      await nextTick()
      await getBuyRecord() // 获取记录
      ls.remove('PAY_TYPE')
      showToast('支付成功')
    })
    .catch(err => {
      // 失败
      ls.remove('PAY_TYPE')
      // 假如有未完结的订单
      if (ls.get('PAY_INFO')) {
        executeFunction()
      } else {
        loading.value = false
      }
    })
}

const lsPayOrder = async(form) => {
  Api.Common.AppObjProcess.Do({
    functionName: 'TemporaryOrderPay',
    contentData: form
  })
    .then(async res => {
      // 成功
      qrcodeShow.value = true
      loading.value = false
   
    })
    .catch(err => {
      // 失败
      loading.value = false
    })
}

// 会员卡升级
const memberUpPay = () => {
  console.log(ls.get('MEMBER_CODE'));

  Api.Common.AppObjProcess.Do({
    functionName: 'MemberUpPay',
    contentData: memberUpPayList.value
  })
    .then(async res => {
      // 成功
      console.log(res)
      memberUpPayRetForm.value.payBatchCode = res.payBatchCode
      memberUpPayRetForm.value.itemCodes = res.itemCode
      loading.value = false
      // console.log(res)
      // console.log(res)
      // 关闭支付弹窗
      cashPayShow.value = false
      setTimeout(() => {
        flag.value = false
      }, 1000)

      // 存 - 消费批次号
      // cartStore.payBatchCode = res.payBatchCode
      // ls.set('PAY_BATCH_CODE', res.payBatchCode)
      // 存 - 已付金额
      // cartStore.payAmt = res.payAmt
      // cartStore.giveChange = res.giveChange
      // cartStore.smallChange = res.smallChange
      await nextTick()
      memberUpPayRecord() // 获取记录
      // ls.remove('PAY_TYPE')
      showToast('支付成功')
    })
    .catch(err => {
      // 失败
      ls.remove('PAY_TYPE')
      // 假如有未完结的订单
      if (ls.get('PAY_INFO')) {
        executeFunction()
      } else {
        loading.value = false
      }
    })
}
// 扫描成功的回调
const onScanSuccess = e => {
  console.log(e[0].rawValue);
  let scanInfo = e[0].rawValue
  Api.Common.AppObjProcess.Do({
    functionName: 'GetMemberInfo',
    contentData: { "encryptData": scanInfo }
  }).then(res => {
    console.log(res);
    cartStore.account = res.result[0].code
    showToast('扫码成功')
    onMember()
  }).catch(err => {
    console.log(err);
    showToast('扫描失败，请重试')
  })
  qrScannerShow.value = false

  return

  const payCode = e[0].rawValue
  const codePrefix = payCode.slice(0, 2)
  const wechatPayCodes = ['10', '11', '12', '13', '14', '15']
  const alipayCodes = ['25', '26', '27', '28', '29', '30']
  let payWay = ''
  let funcName = ''
  if (wechatPayCodes.includes(codePrefix)) {
    payWay = '002'
    funcName = 'weChatPay'
  } else if (alipayCodes.includes(codePrefix)) {
    payWay = '003'
    funcName = 'AliPay'
  } else {
    showToast('无效的付款码')
    return
  }
  cartStore.payInfo.payWay = payWay
  ls.set('PAY_INFO', cartStore.payInfo)
  loading.value = true
  showToast({
    message: '扫描成功',
    position: 'top',
    ['z-index']: 2100
  })
  const params = {
    // 付款码
    payCode: payCode,
    // 支付金额
    payMoney: cartStore.unpaid,
    // 房间码
    roomCode: cartStore.tableInfo.roomCode,
    // 消费码
    consumeCode: cartStore.tableInfo.consumeCode,
    // 订单批次
    orderBatchCode: cartStore.orderBatchCode,
    // 买单批次
    payBatchCode: cartStore.payBatchCode,
    // 操作员名称
    opUser: cartStore.tableInfo.waiterUserName
  }
  Api.Common.AppObjProcess.Do({
    functionName: funcName,
    contentData: params
  })
    .then(res => {
      cartStore.payInfo.tradeNo = res.result
      ls.set('PAY_INFO', cartStore.payInfo)
      getPayState(res.result, payWay)
    })
    .catch(err => {
      loading.value = false
    })
}

const myCanvas = ref(null)
const myCanvasWidth = ref(0)
// ------------------------------------------------------------ 获取二维码链接 --------------------------------------------------------
const getQRCodeUrl = (way, refresh = false) => {
  cartStore.payInfo.roomCode = cartStore.tableInfo.roomCode
  cartStore.payInfo.payWay = way
  ls.set('PAY_INFO', cartStore.payInfo)
  let funcName = ''
  if (way == '002') {
    funcName = 'weChatNativePay'
  } else if (way == '003') {
    funcName = 'AliPayPrecreate'
  }
  const params = {
    // 支付金额
    payMoney: Number(formatDecimal(cartStore.unpaid)),
    // 房间码
    roomCode: cartStore.tableInfo.roomCode,
    // 消费码
    consumeCode: cartStore.tableInfo.consumeCode,
    // 订单批次
    orderBatchCode: cartStore.orderBatchCode,
    // 买单批次
    payBatchCode: cartStore.payBatchCode,
    // 操作员名称
    opUser: cartStore.waiterUserName,
    // 商品或者订单名称
    subject: appStore.user_info.orgName
  }
  if (route.query.type == 'levelUp') {
    params.type = '2'
  }
  Api.Common.AppObjProcess.Do({
    functionName: funcName,
    contentData: params
  })
    .then(async res => {
      console.log(res)

      cartStore.payInfo.tradeNo = res.outTradeNo
      cartStore.payInfo.qrCode = await QRCode.toDataURL(res.qrCode)
      if (refresh) {
        loading.value = false
        showToast({
          message: '二维码已刷新',
          position: 'top'
        })
      }
      ls.set('PAY_INFO', cartStore.payInfo)
      isCanclePay.value = true // 二维码弹窗关闭时取消订单
      loading.value = false
      

      onPay(cartStore.payInfo.payWay) // 临时买单
      onCountDown()
      nextTick(() => {
        // 二维码宽高都用这个参数，+1防止白边
        // myCanvasWidth.value = myCanvas.value.clientWidth+1
        getPayState(cartStore.payInfo.tradeNo, cartStore.payInfo.payWay)
      })
    })
    .catch(err => {
      loading.value = false
    })
}

// 刷新二维码
const onRefreshQRCode = () => {
  if (!cartStore.expire) return
  const cancelFuncName =
    cartStore.payInfo.payWay == '002' ? 'weChatNativeClose' : 'AliPayCancel'
  Api.Common.AppObjProcess.Do({
    functionName: cancelFuncName,
    contentData: { out_trade_no: cartStore.payInfo.tradeNo }
  })
  loading.value = true
  const payWay = cartStore.payInfo.payWay
  cartStore.ClearPayInfo()
  getQRCodeUrl(payWay, true)
}

// 监听是否倒计时结束
watch(
  () => cartStore.expire,
  async nVal => {
    console.log(cartStore.expire);
    if (nVal) {
      await unref(polling).stop()
      clearTimeout(unref(countTimer)) // 定时器清空
      const cancelFuncName =
        cartStore.payInfo.payWay == '002' ? 'weChatNativeClose' : 'AliPayCancel'
      Api.Common.AppObjProcess.Do({
        functionName: cancelFuncName,
        contentData: { out_trade_no: cartStore.payInfo.tradeNo }
      })
    }
  }
)

// 倒计时关闭二维码
const countTimer = ref(null)
const onCountDown = () => {
  if (cartStore.payInfo.countKey < 1) {
    clearTimeout(unref(countTimer))
    return
  }
  countTimer.value = setTimeout(() => {
    cartStore.payInfo.countKey--
    ls.set('PAY_INFO', cartStore.payInfo)
    onCountDown()
  }, 1e3)
}

// 关闭二维码弹窗开始轮询支付结果 （如果二维码没过期 二次提示  否则直接关闭）
const onCloseQRCode = () => {
  // 二维码未过期
  if (!cartStore.expire) {
    cancelPayShow.value = true
    return false
  }
  afterCancelPay()
}

// 关闭二维码后的操作(弹窗关闭后自动触发)
const onClosedQRCode = async () => {
  await unref(polling).stop()
  onCancelQRCode()
}

// 二次确认是否取消二维码订单
const onCancelPay = () => {
  afterCancelPay()
}

// 关闭二维码交易的操作
const afterCancelPay = () => {
  cancelPayShow.value = false
  qrcodeShow.value = false
  return true
}
const isCanclePay = ref(true) // 关闭弹窗时是否取消支付二维码交易
// 撤销二维码交易
const onCancelQRCode = async () => {
  clearTimeout(unref(countTimer))
  if (isCanclePay.value) {
    const cancelFuncName =
      cartStore.payInfo.payWay == '002' ? 'weChatNativeClose' : 'AliPayCancel'
    await Api.Common.AppObjProcess.Do({
      functionName: cancelFuncName,
      contentData: { out_trade_no: cartStore.payInfo.tradeNo }
    })

  }
  ls.remove('PAY_INFO')
  cartStore.ClearPayInfo()
}

// 轮询支付状态 
const getPayState = (tradeNo, payWay) => {
  const loop = Api.Common.AppObjProcess.Loop(
    apiInstance => {
      polling.value = loop
      const funcName = payWay == '002' ? 'weChatNativeQuery' : 'AliPaySearch'
      // if(funcName == 'AliPaySearch'){
      //   return
      // }
      apiInstance
        .Do({
          functionName: funcName,
          contentData: { out_trade_no: tradeNo }
        })
        .then(resp => {
          console.log(resp);
          const state = resp.state
          const msg = resp.stateDesc
          switch (state) {
            // 付款成功
            // case 'SUCCESS':
            // case 'TRADE_SUCCESS':
            //   loop.stop()
            //   clearTimeout(unref(countTimer))
            //   // 微信'002'，支付宝'003'
            //   onPay(payWay)
            //   break
            // // 交易失败，交易关闭，交易完结
            // case 'PAYERROR':
            // case 'TRADE_CLOSED':
            // case 'TRADE_FINISHED':
            // case 'CLOSE':
            // case 'CLOSED':
            //   cartStore.payInfo.payType = msg
            //   break
            // // 等待付款
            // case 'USERPAYING':
            // case 'WAIT_BUYER_PAY':
            // case 'NOTPAY':
            //   cartStore.payInfo.payType = msg
            //   break

            // 付款成功
            case 1:
              loop.stop()
              isCanclePay.value = false // 二维码弹窗关闭时不要取消订单(已成功支付)
              clearTimeout(unref(countTimer))
              cancelPayShow.value = false
              qrcodeShow.value = false

              loading.value = false
              // 关闭支付弹窗
              cashPayShow.value = false
              flag.value = false
              showToast('支付成功')
              cartStore.ClearState()
              ls.remove('PAY_BATCH_CODE')
              ls.remove('PAY_TYPE')
              ls.remove('TABLE_INFO')
              ls.remove('MEMBER_CARD_NUMBER')
              ls.remove('PAY_INFO')
              ls.remove('ORDER_FORM')
              ls.remove('ORDER_INFO')
              ls.remove('ORDER_BATCH_CODE')
              ls.remove('CART_LIST')
              ls.remove('ROOM_DETAIL')
              router.replace('/open')
              checkFlag.value = false
              cartStore.payAmt = 0
              cartStore.realPayAmt = 0
              cartStore.totalOrderAmt = 0
              cartStore.giveChange = 0
              cartStore.smallChange = 0
              cartStore.payBatchCode = ''
              cartStore.ClearState()

              // 微信'002'，支付宝'003'
              // onPay(payWay)
              break
            // 交易失败，交易关闭，交易完结
            case 0:
            case 2:
              cartStore.payInfo.payType = msg
              break
            // 等待付款
            case 5:
              cartStore.payInfo.payType = msg
              break
          }
        })
        .catch(err => {
          loop.stop()
          onCancelQRCode()
        })
    },
    { interval: 5e3 }
  )
  loop.exec()
}

const confirmOnlineWxPay = ()=>{
  loading.value = true
  getQRCodeUrl('002')
  onlineWxPay.value = false
}
const confirmOnlineAliPay = ()=>{
  loading.value = true
  getQRCodeUrl('003')
  onlineAliPay.value = false
}

// 先买单的方式要先下单
const orderFirst = async()=>{
      // 先买单的方式要先下单（临时单  付完结账  未付15分钟后取消（后端））
    if(ls.get('PAY_TYPE') == 1){ 
      loading.value = true
      const orderForm = ls.get('ORDER_FORM')
      console.log(orderForm)
      // 如果已经有买过的单 就不要下单了
      if (ls.get('ORDER_INFO')) {
        loading.value = false
        return
      }
      orderForm.payType = '2'
      console.log(orderForm);
      orderForm.marketUser = route.query.marketUser 
      orderForm.marketUserName = route.query.marketUserName 
      calculateOrderQty(orderForm.detail)
      await Api.Common.AppObjProcess.Do({
        functionName: 'orderAdd',
        contentData: orderForm
      }).then(res => {
        ls.set('ORDER_INFO',res)
        cartStore.orderBatchCode = res.orderBatchCode
        ls.set('ORDER_BATCH_CODE', res.orderBatchCode)
        cartStore.goodsOrderStr = res.dataList.map(obj => obj.itemCode).join(',');
        postForm.detailList = cartStore.goodsOrderStr
        onCancelOrderForm.value.itemCodeList = cartStore.goodsOrderStr
        loading.value = false
      }).catch(err=>{
        loading.value = false
        throw new Error('下单报错了'); 
      })
    }
}

// 选择收款方式
const onPayWay = async function (name) {
  console.log(name);
 
  console.log(cartStore.unpaid);
  if(cartStore.unpaid == 0){
    showToast('待付金额为0，无需支付!')
    return
  }
  await orderFirst()
  switch (name) {
    case 'member':
      if (route.query.type == 'levelUp') {
        showToast('会员卡升级不可用会员余额支付')
        return
      }
      const detail = ls.get('ORDER_FORM') ? ls.get('ORDER_FORM').detail : dtOrder.value
      console.log(detail);
      let vipNoPay = []
			detail.forEach(item=>{
				if(item.isUseBalance == '0' && item.itemType != '3'){
					vipNoPay.push(item.goodsName)
				}
			})
			if(vipNoPay && vipNoPay.length >0){
				let title = vipNoPay.splice(',')
        showToast(title + '不可用会员卡余额支付')
					return
			}

      memberShow.value = true
      break
    case 'alipay':
    onlineAliPay.value = true
      break
    case 'wechat':
    onlineWxPay.value = true
      break
    case 'qrcode':
      qrScannerShow.value = true
      break
    case 'cash':
      initCashForm.value = false
      payListForm.giveChange = 0
      payListForm.smallChange = 0
      payListForm.payAmt = ''
      unpaid.value = cartStore.unpaid
      cashPayShow.value = true
      if (route.query.type == 'levelUp') {
        payListForm.payAmt = Math.ceil(Number(route.query.amt))
      }
      break
    case 'pos':
      showToast('当前版本暂不支持')
      break
  }
}

// 验证会员卡
const onMember = function () {
  if (cartStore.account == '') {
    showToast('请输入会员卡号/手机号')
    return
  }
  let mobile = ls.get('SPE_MOBILE')
  if(memberPrice.value){
    if(mobile != cartStore.account){
      showToast('权益价优惠验证的手机号与当前手机号不符')
      return
    }
  }
  onMemberPrice()
  Api.Common.AppObjProcess.Do({
    functionName: 'checkMemberInfo',
    contentData: {
      mobile: cartStore.account
    }
  })
    .then(res => {
      otherPay() // 其它项目添加
      console.log(postForm.serviceAmt)
      ls.set('MEMBER_CARD_NUMBER', cartStore.account)
      router.push({
        path: '/open/orderMember',
        query: { memberPrice: memberPrice.value}
      })
    })
    .catch(err => {
      openMemberShow.value = true
    })
}
// 验证会员能否使用权益价
const onMemberPrice = () => {
  if (cartStore.account == '') {
    showToast('请输入会员卡号/手机号')
    return
  }
  Api.Common.AppObjProcess.Do({
    functionName: 'CheckMemberInfoByMobile',
    contentData: {
      mobile: cartStore.account
    }
  })
    .then(res => {
      console.log(res,'eseses');
      
      if(IsPriceVipPrice.value){
        if(res.result > 0 && recordList.value <= 0){
          ls.set('SPE_MOBILE',cartStore.account)
          console.log(res);
          memberPrice.value = true
          memberPriceShow.value = false
          // 会员差价 = 购物车总金额 - 会员价金额
          console.log(cartStore.totalOrderAmt - cartStore.vipOrderAmt);
          cartStore.vipDiscount = cartStore.totalOrderAmt - cartStore.vipOrderAmt
        }else{
          memberPrice.value = false
          memberPriceShow.value = false
        }
      }else{
        ls.set('SPE_MOBILE',cartStore.account)
        console.log(res);
        memberPrice.value = true
        memberPriceShow.value = false
        // 会员差价 = 购物车总金额 - 会员价金额
        console.log(cartStore.totalOrderAmt - cartStore.vipOrderAmt);
        cartStore.vipDiscount = cartStore.totalOrderAmt - cartStore.vipOrderAmt
      }

      
     
    })
    .catch(err => {
      memberPrice.value = false
      memberPriceShow.value = false
    })
}
// 开通会员
const onOpenMember = () => {
  router.push({
    path: '/onmember/open',
    query: {
      redirect: '/open/orderCashier'
    }
  })
}

// 确认修改备注
const onConfirmRemark = () => {
  remarkMsg.value = unref(remarkEditMsg)
  remarkEditMsg.value = ''
  remarkShow.value = false
}

// 取消订单
const onCancelOrderForm = ref({
  payBatchCode: '', // 如果已经卖过单,就只要传payBatchCode就行
  itemCodeList: ''
})
const onCancelOrder = () => {
  console.log(cartStore.orderBatchCode)
  console.log(cartStore.payBatchCode)
  if (route.query.type == 'levelUp') {
    router.back()
    return
  }
  // 不是先买单
  if (!ls.get('ORDER_INFO')) {
    showToast('支付已取消')
    router.replace('/open')
    cartStore.payBatchCode = ''
    ls.remove('PAY_BATCH_CODE')
    return
  }else{
    let orderInfo = ls.get('ORDER_INFO')
    if (orderInfo && orderInfo.dataList) {
        onCancelOrderForm.value.itemCodeList = orderInfo.dataList.map(obj => obj.itemCode).join(',')
    }
  }
  
  // 如果有支付过，传payBatchCode
  if (cartStore.payBatchCode) {
    onCancelOrderForm.value.payBatchCode = cartStore.payBatchCode
  }

  Api.Common.AppObjProcess.Do({
    functionName: 'OrderCancelV2',
    contentData: onCancelOrderForm.value
  }).then(async res => {
    showToast('订单已取消')
    await cartStore.ClearState()
    ls.remove('ORDER_BATCH_CODE')
    ls.remove('PAY_BATCH_CODE')
    ls.remove('TABLE_INFO')
    ls.remove('MEMBER_CARD_NUMBER')
    ls.remove('PAY_INFO')
    ls.remove('PAY_TYPE')
    ls.remove('ORDER_FORM')
    ls.remove('ROOM_DETAIL')
    ls.remove('ORDER_INFO')
    cartStore.ClearState()
    router.replace('/open')
  })
}
// 结账
const checkOutForm = ref({
  payBatchCode: '',
  itemCodeList: ''
})

// 押金大于商品金额时直接结账
const checkBookAmt = async()=>{
    postForm.payList = []
   
    // 赋值消费批次号
    postForm.payBatchCode = cartStore.payBatchCode
    // 点单商品金额
    postForm.orderAmt = cartStore.totalOrderAmt
    // 支付列表
    postForm.payList.push(payListForm)
    console.log(payListForm);
    otherPay() // 其它项目添加
   
    // 买单
    if (ls.get('PAY_TYPE') == 1) {
      // 先下单 再买单
      const orderForm = ls.get('ORDER_FORM')
      // 如果已经有买过的单 点单就要传orderBatchCode(第一次买单不用)
      // if (ls.get('ORDER_BATCH_CODE')) {
      //   orderForm.orderBatchCode = ls.get('ORDER_BATCH_CODE')
      // }
      orderForm.payType = '2'
    
      calculateOrderQty(orderForm.detail)
      orderForm.marketUser = route.query.marketUser 
      orderForm.marketUserName = route.query.marketUserName 
      await Api.Common.AppObjProcess.Do({
        functionName: 'orderAdd',
        contentData: orderForm
      }).then(async res => {
        console.log(res)
        cartStore.orderBatchCode = res.orderBatchCode
        ls.set('ORDER_BATCH_CODE', res.orderBatchCode)
        cartStore.goodsOrderStr = res.dataList.map(obj => obj.itemCode).join(',')
        postForm.detailList = cartStore.goodsOrderStr
        onCancelOrderForm.value.itemCodeList = cartStore.goodsOrderStr
        // serviceAmtForm.code =
        if(bookAmt.value > 0){
          let obj = {
            cardNo : bookCardNo.value,
            tradeNo : bookTradeNo.value,
            payType : bookPayType.value,              // 会员优惠用会员价  减去其它优惠
            payAmt : memberPrice.value ? Number((cartStore.vipOrderAmt - totalSelectedMoney.value).toFixed(2)) : Number((cartStore.totalOrderAmt - totalSelectedMoney.value).toFixed(2)),
            totalAmt : memberPrice.value ? Number((cartStore.vipOrderAmt - totalSelectedMoney.value).toFixed(2)) : Number((cartStore.totalOrderAmt - totalSelectedMoney.value).toFixed(2)),
            isReservePay:'1'
          }
          postForm.payList = [obj]
          postForm.payType = bookPayType.value
          postForm.realPayAmt = memberPrice.value ? Number((cartStore.vipOrderAmt - totalSelectedMoney.value).toFixed(2)) : Number((cartStore.totalOrderAmt - totalSelectedMoney.value).toFixed(2))
          postForm.tradeNo = bookTradeNo.value
          bookAmtTool.value = postForm
          // bookAmtTool.value.payBatchCode = ls.get('PAY_BATCH_CODE')
        }
        await Api.Common.AppObjProcess.Do({  // 支付
          functionName: 'orderPay',
          contentData: bookAmtTool.value
        })
          .then(async res => {
            // 成功
            console.log(res)
            loading.value = false
            // 关闭支付弹窗
            cashPayShow.value = false
            setTimeout(() => {
              flag.value = false
            }, 1000)
            ls.remove('PAY_TYPE')
            showToast('支付成功')

            // 存 - 消费批次号
            cartStore.payBatchCode = res.payBatchCode
            ls.set('PAY_BATCH_CODE', res.payBatchCode)
            const toolConsumeCode = ls.get('TABLE_INFO').consumeCode 
              checkOutForm.value.payBatchCode = cartStore.payBatchCode
              checkOutForm.value.itemCodeList = postForm.detailList
              // checkOutForm.value
              Api.Common.AppObjProcess.Do({
                functionName: 'Checkout',
                contentData: checkOutForm.value
              }).then(res => {
                showToast(res.result)
                ls.remove('ORDER_BATCH_CODE')
                ls.remove('PAY_BATCH_CODE')
                ls.remove('TABLE_INFO')
                ls.remove('MEMBER_CARD_NUMBER')
                ls.remove('PAY_INFO')
                ls.remove('CART_LIST')
                ls.remove('ORDER_FORM')
                ls.remove('PAY_TYPE')
                ls.remove('ROOM_DETAIL')
                router.replace('/open')
                cartStore.payAmt = 0
                cartStore.realPayAmt = 0
                cartStore.totalOrderAmt = 0
                cartStore.giveChange = 0
                cartStore.smallChange = 0
                cartStore.payBatchCode = ''
                cartStore.ClearState()
                checkFlag.value = true
                // cartStore.discountAmt = 0
                setTimeout(() => {
                  Api.Common.AppObjProcess.Do({
                  functionName: 'OrderPayPrint',
                  contentData: { consumeCode: toolConsumeCode, payBatchCode: checkOutForm.value.payBatchCode, isAdd: IsAdd.value }
                  }).then(res => {
                    console.log(res);
                  })
                }, 800);
               
              })
            
          })
          .catch(err => {
            // 失败
            if(ls.get('PAY_TYPE') == 1){
                Api.Common.AppObjProcess.Do({
                    functionName: 'OrderCancelV2',
                    contentData: onCancelOrderForm.value
                }).then(async res => {
                    // showToast('支付失败，订单取消')
                    // await cartStore.ClearState()
                    ls.remove('ORDER_BATCH_CODE')
                    ls.remove('PAY_BATCH_CODE')
                    // ls.remove('TABLE_INFO')
                    // ls.remove('MEMBER_CARD_NUMBER')
                    // ls.remove('PAY_INFO')
                    // ls.remove('PAY_TYPE')
                    // ls.remove('ORDER_FORM')
                    // ls.remove('ROOM_DETAIL')
                    // cartStore.ClearState()
                    // router.replace('/open')
                })
            }
            // ls.remove('PAY_TYPE')
            // 假如有未完结的订单
            if (ls.get('PAY_INFO')) {
              executeFunction()
            } else {
              loading.value = false
            }
          })


      })
    }
  
    

  
}

// 结账
const checkFlag = ref(false)
const onCheckout = async() => {
  console.log(cartStore.totalOrderAmt,cartStore.giveChange,cartStore.payAmt,cartStore.discountAmt,cartStore.vipDiscount);
  console.log(cartStore.unpaid);
  
  // return Number(state.totalOrderAmt) + Number(state.giveChange) - Number(state.payAmt)  - Number(state.discountAmt) - Number(state.vipDiscount)
  if(checkFlag.value){
    showToast('加载中，请稍等')
    return
  }
  checkFlag.value = true
  if(cartStore.unpaid == 0 && bookAmt.value >= cartStore.totalOrderAmt){
    await checkBookAmt()
    
  }else{
    if (cartStore.unpaid > 0) {
      showToast('请选择收款方式')
      checkFlag.value = false
      return
    }
  
    // 会员卡升级
    if (route.query.type == 'levelUp') {
      Api.Common.AppObjProcess.Do({
        functionName: 'UpdateMemberLevel',
        contentData: { cardNo: memberUpPayList.value.cardNo }
      }).then(res => {
        showToast(res.result)
        ls.remove('MEMBER_CODE')
        router.back()
        // cartStore.discountAmt = 0
      })
      return
    }
      // if (cartStore.payBatchCode == '') {
      //     cartStore.payBatchCode = ls.get('PAY_BATCH_CODE')
      // }

      const toolConsumeCode = ls.get('TABLE_INFO').consumeCode 
      checkOutForm.value.payBatchCode = cartStore.payBatchCode
      Api.Common.AppObjProcess.Do({
        functionName: 'Checkout',
        contentData: checkOutForm.value
      }).then(res => {
        showToast(res.result)
        ls.remove('ORDER_BATCH_CODE')
        ls.remove('PAY_BATCH_CODE')
        ls.remove('TABLE_INFO')
        ls.remove('MEMBER_CARD_NUMBER')
        ls.remove('PAY_INFO')
        ls.remove('CART_LIST')
        ls.remove('ORDER_FORM')
        ls.remove('PAY_TYPE')
        ls.remove('ROOM_DETAIL')
        router.replace('/open')
        checkFlag.value = false
        cartStore.payAmt = 0
        cartStore.realPayAmt = 0
        cartStore.totalOrderAmt = 0
        cartStore.giveChange = 0
        cartStore.smallChange = 0
        cartStore.payBatchCode = ''
        cartStore.ClearState()

        // cartStore.discountAmt = 0
        Api.Common.AppObjProcess.Do({
        functionName: 'OrderPayPrint',
        contentData: { consumeCode: toolConsumeCode, payBatchCode: checkOutForm.value.payBatchCode, isAdd: IsAdd.value }
        }).then(res => {
          console.log(res);
        })
      })

  }

 
}

const hasPay = ref(false) // 是否已支付 已支付无法使用其它项目配置
const dtOrder = ref([]) // 返回的商品数组
// 获取买单记录（已买单）
const getBuyRecord = async() => {
  
  if (cartStore.orderBatchCode == '') {
    cartStore.orderBatchCode = ls.get('ORDER_BATCH_CODE')
  }
  if (cartStore.payBatchCode == '') {
    cartStore.payBatchCode = ls.get('PAY_BATCH_CODE')
  }
  if (cartStore.tableInfo.roomName == '') {
    cartStore.tableInfo = ls.get('TABLE_INFO')
  }
  console.log(cartStore.tableInfo.consumeCode)
  Api.Common.AppObjProcess.Do({
    functionName: 'getOrderPayNew',
    contentData: {
      roomCode: cartStore.tableInfo.roomCode,
      consumeCode: cartStore.tableInfo.consumeCode,
      payBatchCode: cartStore.payBatchCode
    }
  }).then(res => {
    console.log(res)
    if(res.consumePayList && res.consumePayList.length > 0){
      hasPay.value = true
    }else{
      hasPay.value = false
    }
    cartStore.totalOrderAmt = res.totalOrderAmt
    cartStore.payAmt = res.payAmt + res.prePayAmt // 加上赠送金额支付的金额
    
    cartStore.giveChange = res.giveChange
    // cartStore.smallChange = res.smallChange
    cartStore.realPayAmt = res.realAmt
    cartStore.vipOrderAmt = res.totalVipAmt
    recordList.value = res.consumePayList
    postForm.detailList = res.detailList
    dtOrder.value = res.dtOrder
    checkOutForm.value.itemCodeList = res.detailList
    onCancelOrderForm.value.itemCodeList = res.detailList
    postForm.consumeCode = cartStore.tableInfo.consumeCode
    postForm.roomCode = cartStore.tableInfo.roomCode
    postForm.payUser = cartStore.tableInfo.waiterUserCode
    console.log(res.serviceList)
    // 其它项目显示
    res.serviceList.forEach(item => {
      console.log(item)
      switch (item.type) {
        case '抹零':
          giveChange.value.isSelected = true
          giveChange.value.value = item.amt
          giveChangeAmt.value = item.amt
          break

        case '折扣优惠':
          zkMoney.value.isSelected = true
          zkMoneyAmt.value = item.amt
          if (item.subType == '按金额优惠') {
            zkMoney.value.value = item.amt
            serceSelected.value = 0
          }
          if (item.subType == '按折扣优惠') {
            zkMoney.value.value =
              (10 * (Number(res.totalOrderAmt) - Number(item.amt))) /
              Number(res.totalOrderAmt)
            serceSelected.value = 1
          }
          if (item.subType == '输入付款金额') {
            zkMoney.value.value = Number(res.totalOrderAmt) - Number(item.amt)
            serceSelected.value = 2
          }
          break

        case '服务费':
          serveMoney.value.isSelected = true
          serveMoneyAmt.value = item.amt
          if (item.subType == '按固定金额') {
            serveMoney.value.value = Number(item.amt)
          }
          if (item.subType == '按百分比') {
            serveMoney.value.value =
              (Number(item.amt) / Number(res.totalOrderAmt)) * 100
            serveSelected.value = 1
          }
          break

        case '补低消':
          buMoney.value.isSelected = true
          buMoney.value.value = item.amt
          buMoneyAmt.value = item.amt
          break
        case '会员折扣优惠':
          memberPrice.value = true
          cartStore.vipDiscount = item.amt
          break
      }
    })
      console.log(cartStore.unpaid);
      
      // 代付金额为0 自动调用结账按钮 无需再点击结账按钮
      if(cartStore.unpaid == 0){ 
            onCheckout()
      }

    // 判断是否支付完成
    //  if (cartStore.realPayAmt + cartStore.smallChange >= cartStore.totalOrderAmt) {
    //     showToast('支付完成')
    //     cartStore.ClearState()
    //     ls.remove('PAY_BATCH_CODE')
    //     ls.remove('PAY_TYPE')
    //     ls.remove('TABLE_INFO')
    //     ls.remove('MEMBER_CARD_NUMBER')
    //     ls.remove('PAY_INFO')
    //     clearTimeout(unref(timeoutId))
    //     clearTimeout(unref(countTimer))
    //     router.replace('/open')
    //     return
    // } else {
    //     ls.remove('PAY_TYPE')
    //     showToast('支付成功')
    // }
    // 假如有未完结的订单
    if (ls.get('PAY_INFO')) {
      cartStore.payInfo = ls.get('PAY_INFO')

      // console.log(cartStore.payInfo.roomCode)
      // console.log(cartStore.tableInfo.roomCode)
      // return
    }
    if (
      ls.get('PAY_INFO') &&
      cartStore.payInfo.roomCode == cartStore.tableInfo.roomCode &&
      !cartStore.expire
    ) {
      qrcodeShow.value = true
      onCountDown()
      nextTick(() => {
        isInit.value = true
        // myCanvasWidth.value = myCanvas.value.clientWidth+1
        getPayState(cartStore.payInfo.tradeNo, cartStore.payInfo.payWay)
      })
    } else {
      ls.remove('PAY_INFO')
      cartStore.ClearPayInfo()
      isInit.value = true
    }
  })
  await getBookAmt() // 拉取预订押金信息
  if(bookAmt.value > 0){
        bookAmtTool.value.payBatchCode = ls.get('PAY_BATCH_CODE')
        payOrder(bookAmtTool.value)
  }
}

// ---------------------------------------------------------- 会员卡升级 --------------------------------------------------------
// 获取会员卡升级支付记录
const memberUpPayRecord = () => {
  Api.Common.AppObjProcess.Do({
    functionName: 'MemberUpPayRecord',
    contentData: { payBatchCode: memberUpPayRetForm.value.payBatchCode }
  })
    .then(res => {
      console.log(res);
      ls.set('MEMBER_CODE', memberUpPayRetForm.value)
      recordList.value = res.result
      if (res.result.length == 0) {
        cartStore.payAmt = 0
        cartStore.realPayAmt = 0
      } else {
        cartStore.payAmt = res.result[0].realAmt
        cartStore.realPayAmt = res.result[0].realAmt
      }

      // showToast('11111111')
    })
}
const memberUpPayList = ref({
  tee: "",       // 金额
  payType: "",   // 支付类型
  tradeNo: "",   // 商户号
  cardNo: ""     // 会员卡号
})
const memberUpPayRetForm = ref({
  payBatchCode: '',
  itemCodes: ''
})
// 离开页面撤销支付(会员卡升级)
onBeforeUnmount(() => {
  cartStore.payAmt = 0
  if (!memberUpPayRetForm.value.payBatchCode) {
    return
  }
  Api.Common.AppObjProcess.Do({
    functionName: 'MemberUpPayRet',
    contentData: memberUpPayRetForm.value
  })
    .then(res => {
      ls.remove('MEMBER_CODE')
      cartStore.payAmt = 0
      cartStore.realPayAmt = 0
    })

});
const payed = ref('')
const tableConsumeCode = ref('')

onMounted(async()=>{
    tableConsumeCode.value = ls.get("TABLE_INFO").consumeCode
    // 锁台操作
    await Api.Common.AppObjProcess.Do({ "functionName": "LockConsumeCode", "contentData": {consumeCode:tableConsumeCode.value} })
      .then(res => {
          console.log(res);
      })
      .catch(err=>{
        if(ls.get('ORG_CODE') == '0024' || ls.get('ORG_CODE') == '0025'){
          if(ls.get('PAY_TYPE') != 1  ){
            router.back()
          }else{
            showToast('加载完成')
          }
        }else{
          router.back()
        }
       
      })
   
   
    // 获取低消总额
    await Api.Common.AppObjProcess.Do({ "functionName": "GetConsumeMinConTotalAmt", "contentData": {consumeCode:tableConsumeCode.value} })
    .then(res => {
        if(res.consumeCode == tableConsumeCode.value){
          console.log(res);
          payed.value = res.totalAmt
        }
    })
    .catch(err=>{
    })
    // 预订押金
    getBookAmt()

})
const bookAmt = ref(0)
const toolBookAmt= ref(0)
const bookPayType = ref('')
const bookCardNo = ref('')
const bookTradeNo = ref('')
const getBookAmt = async()=>{
// 预订押金
await Api.Common.AppObjProcess.Do({ "functionName": "GetRoomReserveState", "contentData": {roomCode:cartStore.tableInfo.roomCode} })
    .then(res => {
        if(!res.isUseReserveAmt && res.reserveAmt > 0){ //true 已抵扣 false 未抵扣  false可以用
          bookAmt.value = res.reserveAmt
          toolBookAmt.value = res.reserveAmt
          bookPayType.value = res.posPayType
          bookCardNo.value = res.cardNo
          bookTradeNo.value = res.tradeNo
          cartStore.payAmt = cartStore.payAmt + res.reserveAmt
          console.log(res);
          // this.data.carPrice = this.data.carPrice - res.reserveAmt
        }else{
          bookAmt.value = 0
          toolBookAmt.value = 0
        }
    })
    .catch(err=>{
    })
}
onUnmounted(() => {
    Api.Common.AppObjProcess.Do({ "functionName": "UnLockConsumeCode", "contentData": {consumeCode:tableConsumeCode.value} }).then(res => {
        console.log(res);
    })
   
})

let IsAdd = ref(false)
const isUpvip = ref(false)
const IsPriceVipPrice = ref(false) // 是否享受权益价格要校验会员余额
// 获取门店基础配置
const GetBaseInfo = () => {
  Api.Common.AppObjProcess.Do({ functionName: 'GetBaseConfigInfo', contentData: { orgCode: ls.get('ORG_CODE') } }).then(res => {
    console.log(res);
    
      IsPriceVipPrice.value = res.IsPriceVipPrice
  })
}

// 初始化
const onInit = () => {
  GetBaseInfo()
  cartStore.vipDiscount = 0 // 会员价差额清空
  if (route.query.type == 'levelUp') {
    console.log(route.query);
    isUpvip.value = true
    isShowMemberPrice.value = false
    cartStore.totalOrderAmt = Number(route.query.amt)
    cartStore.vipOrderAmt = Number(route.query.amt)
    memberUpPayList.value.tee = Number(route.query.amt)
    memberUpPayList.value.cardNo = route.query.carNo
    if (ls.get('MEMBER_CODE')) {
      memberUpPayRetForm.value = ls.get('MEMBER_CODE')
      memberUpPayRecord()
    }
    return
  }

  console.log(ls.get('PAY_TYPE')) 
  // 计算代付金额（非先买单的要获取支付记录后计算金额）
  if (ls.get('PAY_TYPE') == 1 || ls.get('PAY_TYPE') == 2) {
    IsAdd.value = true
    console.log(ls.get('CART_LIST'))
    const array = ls.get('CART_LIST')
    let total = 0
    let vipTotal = 0
    // 计算满足条件的元素的 orderQty * salePrice 的总和
    array.forEach(item => {
      total += item.num * item.salePrice
      vipTotal += item.num * item.vipPrice
    })
    cartStore.totalOrderAmt = total // 总价格
    cartStore.vipOrderAmt = vipTotal // vip价格
    cartStore.orderBatchCode = ls.get('ORDER_BATCH_CODE')
    const itemCodeForm = ls.get('ORDER_FORM')
    console.log(itemCodeForm)
    // 获取detailList要的商品itemCode字符串
    postForm.detailList = itemCodeForm.detail
      .map(obj => {
        if (obj.itemType == '2' && Array.isArray(obj.goodsInfoDetail)) {
          const itemCodes = obj.goodsInfoDetail.map(item => item.itemCode)
          return [...itemCodes, obj.itemCode].join(',')
        } else {
          return obj.itemCode
        }
      })
      .join(',')
    // 去除重复
    const arr = postForm.detailList.split(',') // 分割成数组
    // 使用 Set 去重
    const set = new Set(arr)
    const uniqueArr = Array.from(set)
    // 将数组转换成字符串
    postForm.detailList = uniqueArr.join(',')
    checkOutForm.value.itemCodeList = postForm.detailList
    onCancelOrderForm.value.itemCodeList = postForm.detailList
  } else {
    getBuyRecord()
  }


  if (ls.get('MEMBER_CARD_NUMBER')) {
    cartStore.account = ls.get('MEMBER_CARD_NUMBER')
  }

  cartStore.tableInfo = ls.get('TABLE_INFO')
  postForm.consumeCode = cartStore.tableInfo.consumeCode
  postForm.roomCode = cartStore.tableInfo.roomCode
  postForm.payUser = cartStore.tableInfo.waiterUserCode
  cartStore.discountAmt = totalSelectedMoney


}

const discountCon = ref(false)
const rounddownCon = ref(false)
const servicechargeCon = ref(false)
const supplyminconsumeCon = ref(false)
const getyhCon = ()=>{
  ls.get('userMenu').map(e => {
        if(e == 'waiter-checkout-discount'){
          discountCon.value = true
        }
  })
  ls.get('userMenu').map(e => {
        if(e == 'waiter-checkout-rounddown'){
          rounddownCon.value = true
        }
  })
  ls.get('userMenu').map(e => {
        if(e == 'waiter-checkout-servicecharge'){
          servicechargeCon.value = true
        }
  })
  ls.get('userMenu').map(e => {
        if(e == 'waiter-checkout-supplyminconsume'){
          supplyminconsumeCon.value = true
        }
  })
}
getyhCon() // 获取使用优惠功能权限
onInit()



</script>
<style scoped lang="scss">
@import './style.scss';

.canusecoins {
  font-family: PingFang SC;
  font-weight: 500;
  font-size: 12px;
  color: #FFCC66;
  margin-top: 10px;
}
.cm-order-header-left {
  width: 175px;
  font-size:15px;
}
.cm-order-header__text {
  font-size: 9px;
}
</style>
